![]() |
|
![]() |
This article is reprinted from the July 1996 issue of
Inside Solaris, a monthly publication of The
Cobb Group.
SCRIPTING TECHNIQUES Conditionally executing shell scriptsYou sometimes might want to run a shell script at a scheduled time to perform some administrative tasks, like making a backup. If you use crontab to schedule your scripts, you're just about set. The only problem we encounter with this technique is that while you normally want to execute the script, there are occasions when you don't. You could remove the appropriate crontab entry when you don't want to execute the script and then reenter it when you do. However, this method is tedious and errorprone. In this article, we'll show you a simpler technique: We'll let the script decide when to execute based on the presence of a particular file. How does the shell decide whether to run?First we need a method to allow the shell script to decide whether to run. It turns out that this is very easy to do. Figure A shows our demonstration shell script, named test. The highlighted lines show the part that checks for the file /locks/test. The heart of the trick is the -e filename clause in the condition section of the if statement. This clause is true if filename specifies a file that exists; otherwise the clause is false. The rest of your shell script remains unchanged. In our demonstration, if the file /locks/test exists, the script prints a message to let you know why it terminated. Then it executes the exit statement to stop processing the script. Figure A #! /bin/ksh # Test whether shell script is allowed to run if [ -e /locks/test ]; then echo "/locks/test exists, script terminated" exit fi # Normal shell script operation starts here echo "Hello, world!" If this shell script finds the file /locks/test, it prints a warning and exits.
|
Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company. Questions? Comments? |